package com.gzhu.knowledgeAdmin.common.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzhu.knowledgeAdmin.entity.Keyword;
import com.gzhu.knowledgeAdmin.entity.Scene;
import com.gzhu.knowledgeAdmin.service.KeywordService;
import com.gzhu.knowledgeAdmin.service.SceneService;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 关键词列表导入处理器
 * @author yangminggui
 * @create 2024-04-18 17:18
 */
public class KeywordImportHandler extends MyImportHandler {

    KeywordService keywordService;

    String gsid;


    // 导入返回信息
    StringBuilder stringBuilder = new StringBuilder();

    List<Keyword> keywordList;

    public KeywordImportHandler(String gsid, List<Keyword> keywordList) {
        this.keywordService = SpringUtil.getBean(KeywordService.class);;
        this.gsid = gsid;
        this.keywordList = keywordList;
    }


    private String getMsg() {
        // 总结信息
        String summaryMsg = StrUtil.format("导入关键词结束：成功{}条，失败{}条；<br/>{}", validCount, invalidCount, stringBuilder.toString());
        return summaryMsg;
    }

    @Override
    public String handle() {

        for (Keyword keyword : keywordList) {

            String name = keyword.getName();

            StringBuilder validationMsg = new StringBuilder();

            // 名称是否为空
            if(!StringUtils.hasLength(name)){
                validationMsg.append("关键词名称为空");
            }else {
                // 判断关键词名字是否重复
                int count = keywordService.count(new QueryWrapper<Keyword>().eq("name", name).eq("gsid", gsid));
                if (count > 0) {
                    validationMsg.append("关键词名称已存在");
                }
            }

            if(validationMsg.length()==0){
                // 设置公司id
                keyword.setGsid(gsid);
                boolean save = keywordService.save(keyword);

                // 插入异常
                if(!save){
                    invalidCount++;
                    stringBuilder.append("第").append(validCount + invalidCount).append("行数据保存失败；<br/>");
                }else {
                    validCount++;
                }
            }else { // 验证错误

                invalidCount++;
                stringBuilder.append("第" + (validCount + invalidCount) + "行数据校验失败：").append(validationMsg + "<br/>");
            }

        }

        return getMsg();

    }
}
